/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.ibatis.extension.keygen;

import com.je.ibatis.extension.toolkit.ParameterUtil;
import com.je.ibatis.session.CustomConfiguration;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.keygen.KeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.session.Configuration;
import org.springframework.util.StringUtils;

import java.sql.Statement;

/**
 * 元数据主键策略路由
 * <p>
 * 当插入语句中的meta标签没有指定tableCode时，使用此策略根据方法参数获取tableCode，动态路由到主键策略
 *
 * @author wangmm@ketr.com.cn
 * @date 2019/11/21
 */
public class MetaRouterKeyGenerator implements KeyGenerator {

    /**
     * 主键策略后缀
     */
    public static final String SELECT_KEY_SUFFIX = "!metaKey";
    private final Configuration configuration;
    private String table = null;

    public MetaRouterKeyGenerator(Configuration configuration) {
        this.configuration = configuration;
    }

    public MetaRouterKeyGenerator(Configuration configuration, String table) {
        this(configuration);
        this.table = table;
    }


    @Override
    public void processBefore(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
        KeyGenerator keyGenerator = routerKeyGenerator(executor, ms, parameter);
        keyGenerator.processBefore(executor, ms, stmt, parameter);
    }

    @Override
    public void processAfter(Executor executor, MappedStatement ms, Statement stmt, Object parameter) {
        KeyGenerator keyGenerator = routerKeyGenerator(executor, ms, parameter);
        keyGenerator.processAfter(executor, ms, stmt, parameter);
    }

    /**
     * 获取 KeyGenerator
     *
     * @param executor  执行器
     * @param ms        当前语句对象
     * @param parameter 方法参数
     * @return org.apache.ibatis.executor.keygen.KeyGenerator
     */
    public KeyGenerator routerKeyGenerator(Executor executor, MappedStatement ms, Object parameter) {
        String tableCode = parseTableCode(executor, ms, parameter);
        String generatorId = tableCode + MetaRouterKeyGenerator.SELECT_KEY_SUFFIX;
        try{
            return configuration.getKeyGenerator(generatorId);
        }catch (IllegalArgumentException e){
            if(configuration instanceof CustomConfiguration){
                //异常时可能时资源表主键策略未生成 初始化资源表表缓存
                ((CustomConfiguration)configuration).getMetaStatementBuilder().builderTable(tableCode);
            }
            return configuration.getKeyGenerator(generatorId);
        }
    }

    /**
     * 从参数中获取 tableCode
     *
     * @param executor  执行器
     * @param ms        当前语句对象
     * @param parameter 方法参数
     * @return java.lang.String
     */
    private String parseTableCode(Executor executor, MappedStatement ms, Object parameter) {
        if (!StringUtils.isEmpty(table)) {
            return table;
        }
        final MetaObject metaParam = configuration.newMetaObject(parameter);
        return ParameterUtil.tableCode(metaParam);
    }
}
